﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

namespace Ice.Toolkit.Utility
{
    /// <summary>
    /// Json序列化,返序列化
    /// </summary>
    public class JSON
    {
        /// <summary>
        /// 将对像序列化JSON字符串
        /// </summary>
        /// <param name="obj">对像</param>
        /// <returns>Json String</returns>
        public static string Stringify(object obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());

            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);

                StringBuilder result = new StringBuilder();

                result.Append(Encoding.UTF8.GetString(ms.ToArray()));

                return result.ToString();
            }
        }

        /// <summary>
        /// 将JSON字符串返序列化对像
        /// </summary>
        /// <typeparam name="ReturnType">对像类型</typeparam>
        /// <param name="json">字符串</param>
        /// <returns>对像</returns>
        public static ReturnType Parse<ReturnType>(string json)
        {
            ReturnType rt;

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ReturnType));

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                rt = (ReturnType)serializer.ReadObject(ms);
            }

            return rt;
        }
    }
}
